<template>
  <div class="exchangePw">
    <!-- 输入密码弹窗 -->
    <elDialog
      title= ''
      :flag= 'passWordAlert'
      name= 'passWordAlert'
      :width= '450'
      :dialogClose= 'closeDialog'>
      <div class="passWordTitle" slot="operation">
        {{$t('myAdd.enterExPw.exPassW')}}<span class="forgetPassw pointer" @click="forgetEntrance">{{$t('myAdd.enterExPw.forgetExPwd')}}</span>
      </div>
      <div class="passWordEnter" slot="content" @click="onfocus" ref="passWordEnterDiv">
        <!-- @keyup="deleteCode($event)" -->
        <input class="input-code" autofocus ref="inputCodeDom" v-model="inputCodeValue" @input="enterPassWord('input', $event.target.value)" type="text" maxlength="6"  @blur="checkForNum()"/>
        <div class="input-item" :class="item.className" v-for="(item, index) in passLeng" :key="index">{{item.num}}</div>
      </div>
      <div slot="options">
        <button @click="closeDialog" class="cancel">{{$t('myAdd.enterExPw.cancel')}}</button>
      </div>
    </elDialog>
    <!-- 输入短信验证码 -->
    <elDialog
      title= ''
      :flag= 'enterSmsAuthCode'
      name= 'enterSmsAuthCode'
      :width= '450'
      :dialogClose= 'closeDialog'>
      <div class="enterSmsAuthCodeTitle" slot="operation">
        {{$t('myAdd.enterExPw.safeVerify')}}
      </div>
      <div class="smsAuthCodeCont" slot="content" v-if="oneStep">
        <template v-for="(item, key, index) in smsAuthCodeForm">
          <inline-input
            v-bind:property = "item"
            v-model = "item.value"
            v-on:onevents = "somethings">
          </inline-input>
        </template>
      </div>
      <div class="exPwdCont" slot="content" v-if="secondStep">
        <inline-input
          v-bind:property = "exchangePwdForm.resetExPwd"
          v-model = "exchangePwdForm.resetExPwd.value"
          v-on:onevents = "somethings"
          @textOrPassword="textOrPassword">
        </inline-input>
      </div>
      <div class="smsAuthCodeFooter" slot="options">
        <button @click="closeDialog" class="cancel">{{$t('myAdd.enterExPw.cancel')}}</button>
        <button @click="forgetPwdConfirm" :class="{readOnly: !secondClick}">{{$t('myAdd.enterExPw.confirm')}}</button>
      </div>
    </elDialog>
    <span v-if="publicInfo"></span>
  </div>
</template>

<script>
  /*
     'passWordAlert'   // 输入交易密码 弹窗 的关闭 展示  的 开关
  *  this.$emit('closePassWordAlert')  // 触发父组件 关闭输入 交易密码 弹窗
  *  this.$emit('submitRequest') // 触发父组件 提交 订单 请求
  * */
  import elDialog from '@/components/common/addCommon/dialog'
  import InlineInput from '@/components/common/inlineInput'
  import { mapState } from 'vuex'
  export default {
    name: 'exchangePw',
    props: ['passWordAlert'],
    components: { elDialog, InlineInput },
    data () {
      return {
        enterSmsAuthCode: false, // 输入短信验证码弹窗
        inputCodeValue: '',
        smsAuthCodeForm: {},
        exchangePwdForm: {},
        inputCodeLeng: 0,
        regex: /^[\d]+$/,
        unRegex: /^[\D]g/,
        smsCodeReg: /^\d{6}$/,
        passLeng: [
          {num: '', className: ''},
          {num: '', className: ''},
          {num: '', className: ''},
          {num: '', className: ''},
          {num: '', className: ''},
          {num: '', className: ''}
        ],
        oneStep: true, // 第一步
        secondStep: false, // 第二步
        secondClick: true,
        ForgetExchangePwd: null, // 忘记交易密码短信类型
        token: null,
        userInfo: {}
      }
    },
    created () {
      this.smsAuthCodeForm = this.smsAuthCodeForm_obj
      this.exchangePwdForm = this.exchangePwdForm_obj
    },
    mounted () {
      this.ForgetExchangePwd = this.operationType.ForgetExchangePwd
    },
    computed: {
      ...mapState({
        publicInfo ({baseData}) {
          if (baseData.isReady && baseData._user) {
            this.userInfo = baseData._user
            return baseData
          } else {
            return false
          }
        },
        operationType ({operationType}) {
          if (operationType) {
            return operationType
          } else {
            return false
          }
        }
      }),
      smsAuthCodeForm_obj () { // 短信表单
        let obj = {}
        let self = this
        if (this.userInfo.googleStatus === 1) {
          Object.assign(obj, {
            googleCode: {
              title: this.Internationalization.googleVerify,
              placeholder: this.Internationalization.enterGoogleVerify,
              formType: 'text',
              type: null,
              name: 'googleCode',
              keyupEnter: function (argument) {
                self.forgetPwdConfirm()
              },
              value: ''
            }
          })
        } else if (this.userInfo.isOpenMobileCheck === 1) {
          Object.assign(obj, {
            smsValidCode: {
              title: this.Internationalization.smsAuthCode,
              placeholder: this.Internationalization.enterSmsVerifyCode,
              formType: 'verifiCode',
              name: 'smsValidCode',
              operationType: this.ForgetExchangePwd, // 忘记交易密码
              startTime: false,
              data: ['aliyunCapcha'],
              keyupEnter: function (argument) {
                self.forgetPwdConfirm()
              },
              value: null
            }
          })
        } else if (this.userInfo.email) {
          // publicInfo 接口里面 没有关于 是否开启邮箱验证的字段返回
          Object.assign(obj, {
            emailValidCode: {
              title: this.Internationalization.emailVerify,
              placeholder: this.Internationalization.enterEmailVerify,
              formType: 'verifiCode',
              name: 'emailValidCode',
              operationType: this.ForgetExchangePwd,
              startTime: false,
              data: ['aliyunCapcha', 'email'],
              focus: true,
              keyupEnter: function (argument) {
                self.forgetPwdConfirm()
              },
              value: null
            }
          })
        }
        return obj
      },
      exchangePwdForm_obj () { // 忘记密码第二部重置交易密码
        const self = this
        return {
          resetExPwd: {
            title: this.Internationalization.exPass,
            placeholder: this.Internationalization.enterNewExPw,
            formType: 'password',
            name: 'resetExPwd',
            value: '',  // 存储表单里面的值
            isShowEye: true,
            keyupEnter: function (argument) {
              self.forgetPwdTwo()
            }
          }
        }
      },
      Internationalization () {
        return {
          passCode: this.$t('myAdd.enterExPw.passCode'), // 验证码已发送
          cancel: this.$t('myAdd.enterExPw.cancel'), // 取消
          smsAuthCode: this.$t('myAdd.enterExPw.smsAuthCode'), // 短信验证码
          exPassW: this.$t('myAdd.enterExPw.exPassW'), // 交易密码
          enterNewExPw: this.$t('myAdd.enterExPw.enterNewExPw'), // 输入新的交易密码
          pleaseCheck: this.$t('myAdd.enterExPw.pleaseCheck'), // 请检查
          enterSmsCode: this.$t('myAdd.enterExPw.enterSmsCode'), // 请输入验证码
          smsCodeMustSix: this.$t('myAdd.enterExPw.smsCodeMustSix'), // 验证码必须是6位数字
          pleaseEnterExPw: this.$t('myAdd.enterExPw.pleaseEnterExPw'), // 请输入交易密码
          exPwMustSixNum: this.$t('myAdd.enterExPw.exPwMustSixNum'), // 交易密码必须是6位数字
          resetExPwSuc: this.$t('myAdd.enterExPw.resetExPwSuc'), // 交易密码重置成功
          googleVerify: this.$t('myAdd.enterExPw.googleVerify'), // 谷歌验证
          enterGoogleVerify: this.$t('myAdd.enterExPw.enterGoogleVerify'), // 输入谷歌验证码
          emailVerify: this.$t('myAdd.enterExPw.emailVerify'), // 邮箱验证
          enterEmailVerify: this.$t('myAdd.enterExPw.enterEmailVerify'), // 输入邮箱验证码
          enterSmsVerifyCode: this.$t('myAdd.enterExPw.enterSmsVerifyCode'), // 输入短信验证码
          exPass: this.$t('myAdd.enterExPw.exPass') // 重置交易密码
        }
      }
    },
    watch: {
      'smsAuthCodeForm_obj' (val) {
        this.smsAuthCodeForm = val
      },
      'exchangePwdForm_obj' (val) {
        this.exchangePwdForm = val
      },
      inputCodeLeng (val, old) {
        if (val === 6) {
          this.verifyExPw()
        }
        if (val < old) {
          this.deleteCode()
        }
      },
      'passWordAlert' (newV) {
        if (newV) {
          this.$nextTick(() => {
            this.$refs.inputCodeDom.focus()
          })
        }
      }
    },
    methods: {
      closeDialog () {
        this.$emit('closePassWordAlert')
        this.enterSmsAuthCode = false
        this.inputCodeValue = ''
        this.inputCodeLeng = 0
        this.passLeng.forEach(item => {
          item.num = ''
          item.className = ''
        })
      },
      somethings (val) {
        if (val.handleType === 'sendCode') {
          this.sendCode(val, this.smsAuthCodeForm)
        }
      },
      // 忘记密码入口
      forgetEntrance () {
        // this.$emit('closePassWordAlert')
        // this.enterSmsAuthCode = true
        // 忘记密码 的接口 暂不调用， 忘记密码 直接 跳转 至修改密码
        this.$router.push({
          path: '/personal/setExPassW'
        })
      },
      // 忘记交易密码 第一步
      forgetPwdOne () {
        let fla = true
        let smsAuthCode
        let params = { smsAuthCode: null, authType: null }
        if (this.userInfo.googleStatus === 1) {
          smsAuthCode = this.smsAuthCodeForm.googleCode.value
          params.authType = 1
        } else if (this.userInfo.isOpenMobileCheck === 1) {
          smsAuthCode = this.smsAuthCodeForm.smsValidCode.value
          params.authType = 2
        } else if (this.userInfo.email) {
          smsAuthCode = this.smsAuthCodeForm.emailValidCode.value
          params.authType = 3
        }
        !smsAuthCode && (fla = false, this.$store.dispatch('setTipState', {text: this.Internationalization.enterSmsCode, type: 'error'}))
        if (smsAuthCode && !this.smsCodeReg.test(smsAuthCode)) {
          fla = false
          this.$store.dispatch('setTipState', {text: this.Internationalization.smsCodeMustSix, type: 'error'})
        }
        if (!fla) {
          return false
        }
        if (!this.secondClick) {
          return false
        }
        this.secondClick = false
        params.smsAuthCode = smsAuthCode
        this.axios({
          url: this.$store.state.url.transactionUrl.forget_exchange_password_one,
          headers: {},
          params: params,
          method: 'post'
        }).then(res => {
          if (res.code.toString() === '0') {
            this.token = res.data.token
            this.oneStep = false
            this.secondStep = true
          } else {
            this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
          }
          this.secondClick = true
        })
      },
      forgetPwdTwo () { // 忘记密码第二步
        let fla = true
        let resetExPwd = this.exchangePwdForm.resetExPwd.value
        !resetExPwd && (fla = false, this.$store.dispatch('setTipState', {text: this.Internationalization.pleaseEnterExPw, type: 'error'}))
        if (resetExPwd && !this.smsCodeReg.test(resetExPwd)) {
          fla = false
          this.$store.dispatch('setTipState', {text: this.Internationalization.exPwMustSixNum, type: 'error'})
        }
        if (!fla) {
          return false
        }
        if (!this.secondClick) {
          return false
        }
        this.secondClick = false
        this.axios({
          url: this.$store.state.url.transactionUrl.forget_exchange_password_two,
          headers: {},
          params: { exchangePwd: resetExPwd, token: this.token },
          method: 'post'
        }).then(res => {
          if (res.code.toString() === '0') {
            this.$store.dispatch('setTipState', {text: this.Internationalization.resetExPwSuc})
            this.enterSmsAuthCode = false
            this.oneStep = true
            this.secondStep = false
          } else {
            this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
          }
          this.secondClick = true
        })
      },
      // 输入密码
      enterPassWord (type, val) {
        this.inputCodeLeng = val.length
        if (val && this.regex.test(val) && this.inputCodeLeng) {
          this.passLeng[this.inputCodeLeng - 1].className = 'available'
          // 密码 密文 以小圆点展示，所以注释下面的代码
          // this.passLeng[this.inputCodeLeng - 1].num = val.substring(this.inputCodeLeng - 1, this.inputCodeLeng)
        }
      },
      // 校验密码
      checkForNum () {
        this.inputCodeValue = this.inputCodeValue.replace(this.unRegex, '')
      },
      // 删除密码
      deleteCode () {
        this.checkForNum()
        this.passLeng[this.inputCodeLeng].className = ''
        this.passLeng[this.inputCodeLeng].num = ''
      },
      // 交易密码校验
      verifyExPw () {
        this.axios({
          url: this.$store.state.url.transactionUrl.verify_exchange_password,
          headers: {},
          params: {exchangeCode: this.inputCodeValue},
          method: 'post'
        }).then(res => {
          if (res.code.toString() === '0') {
            this.closeDialog()
            // 触发父组件提交 订单请求
            this.$emit('submitRequest')
          } else {
            this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
          }
        })
      },
      // 输入密码表单获取焦点
      onfocus () {
        this.$refs.inputCodeDom.focus()
      },
      // 输入验证码  和 重置交易密码弹窗确定按钮事件
      forgetPwdConfirm () {
        this.oneStep && this.forgetPwdOne()
        this.secondStep && this.forgetPwdTwo()
      },
      sendCode (item, payType) { // 发送验证码
        let data = {}
        if (payType[item.name].startTime) return false
        data.operationType = payType[item.name].operationType
        payType[item.name].startTime = true // 开启倒计时
        if (this.userInfo.isOpenMobileCheck === 1) {
          this.commonHttp.smsValidCode(data).then((data) => {
            if (data.code === '0') {
              this.$store.dispatch('setTipState', this.Internationalization.passCode)
            } else {
              payType.smsAuthCode.startTime = false  // 关闭倒计时
              this.$store.dispatch('setTipState', {text: data.msg, type: 'error'})
            }
          })
        } else if (this.userInfo.email) {
          this.commonHttp.emailVaildCode(data).then((data) => {
            if (data.code === '0') {
              this.$store.dispatch('setTipState', this.$t('personal.text_8'))
            } else {
              payType.emailValidCode.startTime = false // 关闭倒计时
              this.$store.dispatch('setTipState', {text: data.msg, type: 'error'})
            }
          })
        }
      },
      // 密码表单 的 眼睛
      textOrPassword () {
        this.exchangePwdForm.resetExPwd.formType = this.exchangePwdForm.resetExPwd.formType === 'password' ? 'text' : 'password'
      }
    }
  }
</script>
